"""
游戏中使用的精灵的基类
@zhtsu
最后一次更新日期：2021-04-09
"""

import pygame
from pygame.locals import *
from res import *

class GameSprite(pygame.sprite.Sprite):
    "游戏动态精灵通过此类创建"
    def __init__(self, name,image_path, width, height, columns, x, y, speed):
        pygame.sprite.Sprite.__init__(self)
        #卡片冷却时间
        self.cooling_time = 0
        #用于区分不同的精灵
        self.name = name
        #控制是否循环播放
        self.is_loop = True
        #移动速度
        self.speed = speed
        #生命值
        self.HP = 5000
        ################
        self.image = None
        self.master_image = pygame.image.load(image_path).convert_alpha()
        self.rect = self.master_image.get_rect()
        self.rect.width = width
        self.rect.height = height
        self.rect.topleft = (x, y)
        self.frame = 0
        self.old_frame = -1
        self.frame_width = width
        self.frame_height = height
        self.first_frame = 0
        self.columns = columns
        self.last_time = 0
        rect = self.master_image.get_rect()
        self.last_frame = (rect.width // width) * (rect.height // height) - 1

    def update(self, current_time, rate=160):
        if current_time > self.last_time + rate:
            self.frame += 1
            if self.frame > self.last_frame:
                if self.is_loop == True:
                    self.frame = self.first_frame
                else :
                    self.frame = self.frame - 1
            self.last_time = current_time
        if self.frame != self.old_frame:
            frame_x = (self.frame % self.columns) * self.frame_width
            frame_y = (self.frame // self.columns) * self.frame_height
            rect = (frame_x, frame_y, self.frame_width, self.frame_height)
            self.image = self.master_image.subsurface(rect)
            self.old_frame = self.frame
        if self.name == "bringer-of-death":
            self.rect.centerx -= self.speed
        elif self.name == "ghost":
            self.rect.centerx -= self.speed - 0.5


    def change_image(self, img_path):
        self.image = pygame.image.load(img_path).convert_alpha()
    def changeAction(self, img_path):
        self.master_image = pygame.image.load(img_path).convert_alpha()
    def getPos(self):
        return self.rect
    def moveByTopLeft(self, final_x, final_y):
        self.rect.x = final_x
        self.rect.y = final_y
    def moveByCenter(self, final_x, final_y):
        self.rect.centerx = final_x
        self.rect.centery = final_y
    def changeSpeed(self, speed):
        self.speed = speed
    def deductHP(self, num):
        self.HP -= num
    def getHP(self):
        return self.HP
    def change_loop(self, switch):
        self.is_loop = switch
    def set_cooling_time(self, cooling_time):
        self.cooling_time = cooling_time
    def get_cooling_time(self):
        return self.cooling_time
    def change_HP(self, HP):
        self.HP = HP